try:
    import ogr
except:
    from osgeo import ogr
try:
    import gdal
except:
    from osgeo import gdal
import os

# os.environ['PROJ_LIB'] = r"/home/冯洋洋/PythonEnvironment/RasterShapeEnv/share/proj"

def add_field(vector_path, field_name, save_dir):
    ogr.RegisterAll()
    datasource = ogr.Open(vector_path)
    layer = datasource.GetLayer()
    geomType = layer.GetGeomType()
    spatial = layer.GetSpatialRef()
    layer_name = layer.GetName()
   
    dest_shp_name = f"{layer_name}.shp"
    dest_shp_path = os.path.join(save_dir, dest_shp_name)
    gdal.SetConfigOption("SHAPE_ENCODING", "GBK")
    driver = ogr.GetDriverByName("ESRI Shapefile")
    dest_datasource = driver.CreateDataSource(dest_shp_path)
    dest_layer = dest_datasource.CreateLayer(
        layer_name, spatial, geomType)
    field_defn = ogr.FieldDefn(field_name, ogr.OFTInteger)
    dest_layer.CreateField(field_defn)
    feature_defn = dest_layer.GetLayerDefn()
    id = 0
    feature = layer.GetNextFeature()
    while feature:
        dest_feature = ogr.Feature(feature_defn)
        dest_feature.SetField(field_name, id)
        geometry = feature.geometry()
        dest_feature.SetGeometry(geometry)
        dest_layer.CreateFeature(dest_feature)
        id += 1
        feature = layer.GetNextFeature()
    datasource.Destroy()
    dest_datasource.Destroy()
    return

if __name__ == "__main__":
    vector_path = r"Z:\冉志祎\柑橘样本\G50F034009.shp"
    field_name = r"AOTU"
    save_dir = r"Z:\冉志祎\temp"
    add_field(vector_path, field_name, save_dir)